import { defineStore } from 'pinia'
import { ref } from 'vue'
import type { IUserInfoVo } from '@/api/types/login'
import type { ILoginForm } from '@/api/login'
import { loginByPwd } from '@/api/login'

// 初始化状态
const userInfoState: IUserInfoVo = {
  id: 0,
  username: '',
  avatar: '/static/images/default-avatar.png',
  token: '',
  userInfo: {},
}

export type Role = 'user' | 'admin'

export const useUserStore = defineStore(
  'user',
  () => {
    const token = ref<string>('')
    const role = ref<Role>('user')
    const userInfo = ref<any>({})

    /**
     * 模拟登录
     * @param userRole 登录的角色
     */
    const login = async (loginForm: ILoginForm, _role: Role) => {
      const res = await loginByPwd({
        username: loginForm.username,
        password: loginForm.password,
      })
      console.log(res)
      token.value = res.result.token
      role.value = _role
      // 模拟用户信息
      userInfo.value = {
        role: _role,
        ...res.result.userInfo,
      }
    }

    /**
     * 登出
     */
    const logout = () => {
      token.value = ''
      role.value = 'user'
      userInfo.value = {}
      uni.switchTab({
        url: '/pages/user/index',
      })
    }

    return {
      token,
      role,
      userInfo,
      login,
      logout,
    }
  },
  {
    persist: true, // 开启持久化
  },
)
